import Vue from "vue";
import VueRouter from "vue-router";

import Login from "../components/Login";
import Home from "../components/Home";
import Welcome from "../components/Welcome";
import Users from "../pages/Users/Users.vue";
import Rights from "../pages/power/Rights.vue";
import Roles from "../pages/power/Roles.vue";
import Category from "../pages/Goods/Category.vue";
import Params from "../pages/Goods/Params.vue";
import GoodsList from "../pages/Goods/GoodsList.vue";
import AddGoods from "../pages/Goods/AddGoods.vue";
import Order from "../pages/Order/Order.vue";
import Report from "../pages/Report/Report.vue";

Vue.use(VueRouter);

const router = new VueRouter({
  routes: [
    {
      // 一级路由  重定向
      path: "/",
      redirect: "/login",
    },
    {
      // 一级路由
      path: "/login",
      component: Login,
    },
    {
      // 一级路由
      path: "/home",
      component: Home,
      redirect: "/home/welcome", //当访问/home时，重定向到其子路由welcome中
      children: [
        {
          // 二级路由  欢迎登录
          path: "welcome",
          component: Welcome,
        },

        {
          // 二级路由  用户列表
          path: "/users",
          component: Users,
        },

        {
          //二级路由  权限列表
          path: "/rights",
          component: Rights,
        },
        {
          // 二级路由  角色列表
          path: "/roles",
          component: Roles,
        },
        {
          //二级路由  商品分类
          path: "/categories",
          component: Category,
        },
        {
          // 二级路由  分类参数
          path: "/params",
          component: Params,
        },
        {
          // 二级路由  商品列表
          path: "/goods",
          component: GoodsList,
        },
        {
          // 二级路由  添加商品信息
          path: "/goods/add",
          component: AddGoods,
        },
        {
          // 二级路由  订单管理
          path: "/orders",
          component: Order,
        },
        {
          // 二级路由  订单管理
          path: "/reports",
          component: Report,
        },
      ],
    },
  ],
});

// 挂载路由守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from  代表从哪个路径跳转而来
  // next  是一个函数，表示放行
  //  next()  直接放行    next('/login)  强制跳转
  if (to.path === "/login") return next();
  // 如果用户要访问的路径是login，则直接放行
  else if (to.path !== "/login") {
    // 如果用户不是访问登录页面，则判断是否携带token令牌(是否为登录状态)
    // 获取token  通过 window.sessionStorage.getItem()  获取存储在本地的token
    const tokenValue = window.sessionStorage.getItem("token");
    // token有可能有值也有可能是空值
    // 如果不存在token值，则强制跳转到登录页
    if (!tokenValue) return next("/login");
    // 存在token，则直接放行
    else return next();
  }
});

export default router;
